package com.example.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

public class ContractAddressManager {

    private static final String CONTRACT_INFO_FILE = "/opt/demo/back/contract_info.properties";

    /**
     * 保存合约地址到配置文件
     *
     * @param contractName 合约名称
     * @param newAddress   新的合约地址
     */
    public static void saveAddressToContractNote(String contractName, String newAddress) {
        Properties properties = new Properties();

        // 加载现有的属性
        try (InputStream input = Files.newInputStream(Paths.get(CONTRACT_INFO_FILE))) {
            properties.load(input);
        } catch (IOException ex) {
            System.err.println("Error loading properties file: " + ex.getMessage());
        }

        // 添加或更新合约地址
        properties.setProperty("address." + contractName, newAddress);

        // 保存属性到文件
        try (FileOutputStream output = new FileOutputStream(CONTRACT_INFO_FILE)) {
            properties.store(output, null);
            System.out.println("Saved new address " + contractName + " -> " + newAddress);
        } catch (IOException ex) {
            System.err.println("Error saving properties file: " + ex.getMessage());
        }
    }

    /**
     * 从配置文件中读取合约地址
     *
     * @param contractName 合约名称
     * @return 合约地址，如果不存在则返回 null
     */
    public static String getAddressFromContractNote(String contractName) {
        Properties properties = new Properties();

        // 加载现有的属性
        try (InputStream input = Files.newInputStream(Paths.get(CONTRACT_INFO_FILE))) {
            properties.load(input);
        } catch (IOException ex) {
            System.err.println("Error loading properties file: " + ex.getMessage());
            return null;
        }

        // 获取合约地址
        String address = properties.getProperty("address." + contractName);
        if (address == null) {
            System.out.println("Address for contract " + contractName + " not found.");
        } else {
            System.out.println("Loaded address " + contractName + " -> " + address);
        }
        return address;
    }
}
